package com.ep.thirdPlatformProject.system.util;


import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
public class FileUtil {

    /**
     * 通过网络地址获取文件InputStream（持续获取）
     *
     * @param urlStr 地址
     * @return inputStream
     */
    public static InputStream returnByteStream(String urlStr) {
        if (StrUtil.isEmpty(urlStr) || !urlStr.matches("^(http|https)://.*$")) {
            throw new RuntimeException("url存在问题，请检查是否可以下载！");
        }
        try {
            // 利用HttpURLConnection对象,我们可以从网络中获取网页数据.
            URL url = new URL(urlStr);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.connect();
            // 得到网络返回的输入流
            InputStream inputStream = conn.getInputStream();
            // 转化为ByteArrayInputStream
            byte[] data = stream2ByteArray(inputStream);
            return new ByteArrayInputStream(data);
        } catch (Exception e) {
            log.error("url文件下载错误！");
            throw new RuntimeException("url文件下载错误！错误原因是:" + e.getMessage(), e);
        }

    }


    /**
     * 获取流中字节数组
     *
     * @param inputStream 输入流
     * @return {@link byte[] }
     */
    public static byte[] stream2ByteArray(InputStream inputStream) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 处理大文件流
        BufferedInputStream bis = new BufferedInputStream(inputStream);
        try {
            byte[] buffer = new byte[2048];
            int len = -1;
            while ((len = bis.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            return outputStream.toByteArray();
        } catch (Exception e) {
            log.error("文件处理出现问题，{}", e.getMessage());
            throw new RuntimeException(e);
        } finally {
            try {
                outputStream.close();
                inputStream.close();
            } catch (Exception e) {
                log.error("输入输出流关闭错误，{}", e.getMessage());
            }
        }
    }
}
